package com.freedom.monitor.filter;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.freedom.monitor.utils.ConstantUtils;
import com.freedom.monitor.utils.CookieUtils;
import com.freedom.monitor.utils.StringUtils;

//暂时是通过token永久生效，除非关闭浏览器解决这个问题 
//@WebFilter(filterName = "MyTokenCheckFilter", urlPatterns = { "/*" })
public class MyTokenCheckFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	private static boolean shouldHaveToken(String s) {
		if (null != s && (//
		s.endsWith(".css")//
				|| s.endsWith(".js")//
				|| s.endsWith(".jpg")//
				|| s.endsWith(".png")//
				|| s.endsWith(".gif")//
				|| s.equals("/myeyeweb/user/login")//
				|| s.equals("/myeyeweb")//
				|| s.equals("myeyeweb/")//
		)) {
			return false;
		}
		return true;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String uri = ((HttpServletRequest) request).getRequestURI();
		HashMap cookieMap = CookieUtils.getCookie((HttpServletRequest) request);
		String userId = (String) cookieMap.get(ConstantUtils.COOKIE_USER_ID);
		String token = (String) cookieMap.get(ConstantUtils.COOKIE_TOKEN);
		if (shouldHaveToken(uri) && false == StringUtils.valid(userId, token)) {
			// 重定向到登录页面
			request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
		} else {
			// 务必继续filter
			chain.doFilter(request, response);
		}

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
